package services;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.APNTemplate;

import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.style.Style6;
import dao.PushDeliveryOrder_Repository;
import models.DatabaseExecutionContext;
import org.apache.commons.collections.CollectionUtils;
import play.db.jpa.JPAApi;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.CompletionStage;

import static java.util.concurrent.CompletableFuture.supplyAsync;

public class PushDeliveryOrder_Repository_JPA implements PushDeliveryOrder_Repository {

    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;
    private static String appId = "H0CGDaJkgX5KuKZm4sOPt9";
    private static String appKey = "0AipfONu0674lSnpZ5ir15";
    private static String masterSecret = "BZlxZS2vC562Rg2NQMQ2V";
    private static String host = "http://sdk.open.api.igexin.com/apiex.htm";

    @Inject
    public PushDeliveryOrder_Repository_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    @Override
    public CompletionStage<String> AppPush(String clientId, String token, String deptId, String mobile) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                SimpleDateFormat fd = new SimpleDateFormat("yyyyMMddHHmmss");
                Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
//                Long now = Long.valueOf(fd.format(calendar.getTime()).replace("\"", "").trim());//当前系统时间
//        System.out.println("====now=====" + now);
                IPushResult ret = null;
                calendar.add(Calendar.DATE, -1);//当前系统时间 的   前5天的时间
                Long tensecondago = Long.valueOf(fd.format(calendar.getTime()).replace("\"", "").trim());

                String pushTime = tensecondago.toString().substring(0, 4) + "-" + tensecondago.toString().substring(4, 6) + "-" + tensecondago.toString().substring(6, 8)+" "+tensecondago.toString().substring(8,10)+":"+tensecondago.toString().substring(10,12)+":"+tensecondago.toString().substring(12,14);
//                System.out.println("====now=====" + pushTime);
                String strSql = "select * from v_pushDeliveryOrder where fd_createDate >= '"+pushTime+"'";
                List<Object> list = entityManager.createNativeQuery(strSql).getResultList();
                if (CollectionUtils.isEmpty(list)) {
                    return "无数据";
                }

                if (clientId == null || "".equals(clientId) || "null".equals(clientId)) {

                    for (int i = 0; i < list.size(); i++) {
                        Object[] log = (Object[]) list.get(i);
//                        if (log[6] == null || log[5] == null) {
////                            continue;
////                        }

//                        Long gpsTime = Long.valueOf(log[6].toString().substring(0, 19).replace("-", "").replace(":", "").replace(" ", ""));

                        if (log[7].toString().equals(deptId)) {
                            IGtPush push = new IGtPush(host, appKey, masterSecret);
                            APNTemplate t = new APNTemplate();
                            APNPayload apnpayload = new APNPayload();
                            apnpayload.setSound("");
                            APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
                            //通知文本消息标题
                            alertMsg.setTitle("温馨提示");
                            //通知文本消息字符串
                            alertMsg.setBody(log[7].toString() + "您有新的计划" + log[8].toString() + "生成");
                            //对于标题指定执行按钮所使用的Localizable.strings,仅支持IOS8.2以上版本
                            alertMsg.setTitleLocKey("ccccc");
                            //指定执行按钮所使用的Localizable.strings
                            alertMsg.setActionLocKey("ddddd");
                            apnpayload.setAlertMsg(alertMsg);

                            t.setAPNInfo(apnpayload);
                            ListMessage message = new ListMessage();
                            message.setData(t);
                            String contentId = push.getAPNContentId(appId, message);
//                            System.out.println(contentId);
                            List<String> dtl = new ArrayList<String>();
                            dtl.add(token);
                            System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
                            ret = push.pushAPNMessageToList(appId, contentId, dtl);
                            System.out.println(ret.getResponse());
                            return ret.getResponse().toString();
                        }
                    }
                } else {

//    System.out.println("====tensecondago=====" + tensecondago);
                    for (int j = 0; j < list.size(); j++) {

                        Object[] log = (Object[]) list.get(j);
//                        if (log[7] == null || log[6] == null) {
//                            continue;
//                        }
                        List<Object> query = entityManager.createQuery("select p from PushLog_T_Entity p where p.deliveryOrderId =:deliveryOrderId and p.deptId =:deptId and p.mobile =:mobile").setParameter("deliveryOrderId", log[8].toString()).setParameter("deptId", Integer.valueOf(deptId)).setParameter("mobile", mobile).getResultList();
                        if (CollectionUtils.isEmpty(query)) {
//        String time = new Timestamp(System.currentTimeMillis()).toString().substring(0,19);
//                            Long gpsTime = Long.valueOf(log[7].toString().substring(0, 19).replace("-", "").replace(":", "").replace(" ", ""));

                            if (log[9].toString().equals(deptId) || deptId.equals("1")) {

//
                                    // 配置返回每个用户返回用户状态，可选
                                    System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
                                    IGtPush push = new IGtPush(host, appKey, masterSecret);
                                    // 通知透传模板
                                    NotificationTemplate template = temp(entityManager, log[8].toString(), log[7].toString());
                                    ListMessage message = new ListMessage();
                                    message.setData(template);
                                    // 设置消息离线，并设置离线时间
                                    message.setOffline(true);
                                    // 离线有效时间，单位为毫秒，可选
                                    message.setOfflineExpireTime(24 * 1000 * 3600);
                                    // 配置推送目标
                                    List targets = new ArrayList();
                                    if (clientId.indexOf(",") != -1) {
                                        String[] cid = clientId.split(",");
                                        for (int i = 0; i < cid.length; i++) {
                                            Target target = new Target();
                                            target.setAppId(appId);
                                            target.setClientId(cid[i]);
                                            targets.add(target);
                                        }
                                    } else {
                                        Target target = new Target();
                                        target.setAppId(appId);
                                        target.setClientId(clientId);
                                        targets.add(target);
                                    }
                                    try {
                                        // taskId用于在推送时去查找对应的message
                                        String taskId = push.getContentId(message);
                                        ret = push.pushMessageToList(taskId, targets);
                                        if (ret != null && isPushSuccess(ret)) {
                                            String sqlIn = "insert into pushLog([pushTime],[deptId],[mobile],[deliveryOrderId]) values ('" + new Timestamp(System.currentTimeMillis()).toString() + "','" + deptId + "','" + mobile + "','" + log[8].toString() + "')";
                                            entityManager.createNativeQuery(sqlIn).executeUpdate();
                                        }
                                        System.out.println(ret.getResponse().toString());
//                return ret.getResponse().toString();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        return "服务器异常";
                                    }



                            }
                        }
                    }

                }

                if (ret != null && isPushSuccess(ret)) {


                    return "消息推送成功";


                } else {


                    return "无消息推送";

                }


            });
        }, executionContext);
    }

    private boolean isPushSuccess(IPushResult result) {

        if (result.getResponse() != null && result.getResponse().get("result").toString().equals("ok")) {

            return true;

        }

        return false;

    }

    public static NotificationTemplate temp(EntityManager em, String getWJ, String LastTime) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(1);
        template.setTransmissionContent("{'title':'安卓透传标题','content':'安卓透传内容','payload':'安卓透传数据'}");
        // 设置定时展示时间
        // template.setDuration("2015-01-16 11:40:00", "2015-01-16 12:24:00");

        Style6 style = new Style6();
        // 设置通知栏标题与内容
        style.setTitle("温馨提示");
        style.setText(LastTime + "您有新的计划" + getWJ + "生成");
//        style.setBigStyle2(LastTime + "您有新的计划" + getWJ + "生成");
        style.setBigStyle1("https://thumbnail0.baidupcs.com/thumbnail/b8f4a280597ecc41560fc21a020dd698?fid=1698552189-250528-82789298572194&time=1528423200&rt=sh&sign=FDTAER-DCb740ccc5511e5e8fedcff06b081203-0oUVcKh6DRQkKKv8eGuqggEt12k%3D&expires=8h&chkv=0&chkbd=0&chkpc=&dp-logid=3674710342706909484&dp-callid=0&size=c710_u400&quality=100&vuk=-&ft=video");
        // 配置通知栏图标
        style.setLogo("icon.png");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);
//        // 设置通知栏标题与内容
//        Style6 style = new Style6();
//        style.setBigStyle2(LastTime + "您有新的计划" + getWJ + "生成");
//        template.setTitle("温馨提示");
//        template.setText(LastTime + "您有新的计划" + getWJ + "生成");
//        // 配置通知栏图标
//        template.setLogo("icon.png");
//        // 配置通知栏网络图标
//        template.setLogoUrl("");
//        // 设置通知是否响铃，震动，或者可清除
//        template.setIsRing(true);
//        template.setIsVibrate(true);
//        template.setIsClearable(true);
//        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
//        template.setTransmissionType(1);
//        template.setTransmissionContent("{'title':'安卓透传标题','content':'安卓透传内容','payload':'安卓透传数据'}");
//        template.setStyle(style);
        return template;
    }
}
